package com.twu.biblioteca;

import com.twu.biblioteca.library.Library;
import com.twu.biblioteca.login.LoginFilter;
import com.twu.biblioteca.options.Option;
import com.twu.biblioteca.streams.AppOutputStream;
import com.twu.biblioteca.streams.UserInputStream;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BibliotecaApp {
    private Options options;
    private Library library;

    public BibliotecaApp() {
        this.library = Library.getLibrary();
        this.options = new Options();
    }

    public void setOptions(Options options) {
        this.options = options;
    }

    public void setLibrary(Library library) {
        this.library = library;
    }

    public static void main(String[] args) throws IOException {
        UserInputStream.initUserInputStream(new BufferedReader(new InputStreamReader(System.in)));
        AppOutputStream.initAppOutputStream(System.out);
        new BibliotecaApp().run();
    }

    public void run() throws IOException {
        while (true) {
            showWelcomeMessageAndOptionList();
            String userInput = getUserInput();
            Option option = getOption(userInput);
            filterOption(option);
            executeOption(option);
            if (isExitSystemOption(option)) {
                break;
            }
            AppOutputStream.writeLine("\n\n");
        }
    }

    private void showWelcomeMessageAndOptionList() throws IOException {
        AppOutputStream.writeLine("Welcome to TWU Biblioteca !\n");
        AppOutputStream.writeLine(options.toString());
        AppOutputStream.writeLine("Please enter your option:\n");
    }

    private String getUserInput() throws IOException {
        return UserInputStream.readLine();
    }

    private Option getOption(String userInput) {
        return options.getOptionFromOptionNumber(userInput);
    }

    private void filterOption(Option option) throws IOException {
        new LoginFilter().doFilter(option);
    }

    private void executeOption(Option option) throws IOException {
        option.execute();
    }

    private boolean isExitSystemOption(Option option) {
        String optionDesc = option.toString();
        return "Exit System".equals(optionDesc);
    }
}
